// Package database @program: account
//@author: edte
//@create: 2021-12-28 14:49
package database

import (
	log2 "account/log"
	"account/tools"
	"context"
	"errors"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"strconv"
)

func AdminQueryData(startId int, endId int) ([]tools.User, error) {
	mysqlPath := tools.GetEnv("MYSQL_PATH", "localhost:3306")
	mysqlUser := tools.GetEnv("MYSQL_USER", "root")
	mysqlPassword := tools.GetEnv("MYSQL_PASSWORD", "123456")
	db, err := gorm.Open(mysql.Open(mysqlUser+":"+mysqlPassword+"@tcp("+mysqlPath+")/users?charset=utf8&parseTime=True&loc=Local"), &gorm.Config{})

	// db, err := gorm.Open(mysql.Open("root:123456@tcp(localhost:3306)/users?charset=utf8&parseTime=True&loc=Local"), &gorm.Config{})
	if err != nil {

		writeLog, err2 := log2.WriteLog(context.Background(), "account", "AdminQueryData", "("+strconv.Itoa(startId)+","+strconv.Itoa(endId)+")", "Error", "failed to connect database")
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}

		return nil, errors.New("failed to connect database")
	}
	var tmpUser []tools.User
	db.Model(tools.User{}).Where("id >=  ? AND id <= ?", startId, endId).Find(&tmpUser)
	if len(tmpUser) < 1 {
		writeLog, err2 := log2.WriteLog(context.Background(), "account", "AdminQueryData", "("+strconv.Itoa(startId)+","+strconv.Itoa(endId)+")", "Warring", "The query fails")
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return nil, errors.New("the query fails")
	}
	var users []tools.User
	for _, user := range tmpUser {
		users = append(users, user)
	}
	return users, err

}
